const slider = document.getElementById("slider");
const thumb = document.getElementById("thumb");
const labels = slider.querySelectorAll(".slider-labels span");
const selectedLetterEl = document.getElementById("selected-letter");
const trackBlocks = slider.querySelectorAll(".track-block");

const count = labels.length;
const positions = []; // 每个字母/块的百分比位置

// 计算每个块的中心位置百分比
trackBlocks.forEach((block, i) => {
  const rect = slider.getBoundingClientRect();
  const blockRect = block.getBoundingClientRect();
  const sliderLeft = rect.left;
  const centerPx = blockRect.left - sliderLeft + blockRect.width / 2;
  positions.push(centerPx); // 保存像素位置
});

let currentIndex = 0;

function updateThumb (index) {

  // 对齐滑块到块中心
  const rect = slider.getBoundingClientRect();
  const percent = (positions[index] / rect.width) * 100;
  thumb.style.left = percent + "%";
  selectedLetterEl.textContent = labels[index].textContent;
}

function dragThumb () {
  let rect = slider.getBoundingClientRect();

  function onMove (e) {
    let x = e.clientX - rect.left;
    x = Math.max(0, Math.min(x, rect.width));

    // 找到最近的块中心
    let closestIndex = 0;
    let minDist = Infinity;
    positions.forEach((pos, i) => {
      const dist = Math.abs(pos - x);
      if (dist < minDist) {
        minDist = dist;
        closestIndex = i;
      }
    });

    currentIndex = closestIndex;
    updateThumb(currentIndex);
  }

  function onUp () {
    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onUp);
  }

  document.addEventListener("mousemove", onMove);
  document.addEventListener("mouseup", onUp);
}

thumb.addEventListener("mousedown", dragThumb);

// 点击轨道跳到最近块
slider.addEventListener("click", (e) => {
  if (e.target !== thumb) {
    const rect = slider.getBoundingClientRect();
    let x = e.clientX - rect.left;
    x = Math.max(0, Math.min(x, rect.width));

    let closestIndex = 0;
    let minDist = Infinity;
    positions.forEach((pos, i) => {
      const dist = Math.abs(pos - x);
      if (dist < minDist) {
        minDist = dist;
        closestIndex = i;
      }
    });

    currentIndex = closestIndex;
    updateThumb(currentIndex);
  }
});

// 初始化
window.addEventListener("load", () => {
  // 重新计算块中心位置，保证响应式
  positions.length = 0;
  trackBlocks.forEach((block) => {
    const rect = slider.getBoundingClientRect();
    const blockRect = block.getBoundingClientRect();
    const sliderLeft = rect.left;
    const centerPx = blockRect.left - sliderLeft + blockRect.width / 2;
    positions.push(centerPx);
  });
  updateThumb(currentIndex);
});

// 窗口大小变化时更新位置
window.addEventListener("resize", () => {
  positions.length = 0;
  trackBlocks.forEach((block) => {
    const rect = slider.getBoundingClientRect();
    const blockRect = block.getBoundingClientRect();
    const sliderLeft = rect.left;
    const centerPx = blockRect.left - sliderLeft + blockRect.width / 2;
    positions.push(centerPx);
  });
  updateThumb(currentIndex);
});